// pages/my/balance/balance.js
var UUID = require('../../../utils/Math.uuid.js');
var utils = require('../../../utils/util.js');
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isFirst: '1',
    sexSets: [{
      value: '男',
      checked: 'true'
    }, {
      value: '女',
      checked: 'false'
    }],
    birthdaystr: '1990-01-01',
    birth: {
      year: '1990',
      month: '01',
      day: '01'
    },
    isAgree: '1',
    isAgree2: '1',
    rctype: '1',
    sum: '200',
    isPassword: true,
    tipshow:false,
    username:'',
    phone:'',
    msgCode:'',
    sexval: '1'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var isFisrt = '0';
    if (app.globalData.personInfo.USERNAME == '') {
      isFisrt = '1';
    }
    this.setData({
      isFirst: isFisrt
    });
    this.loadBalance();
  },
  loadBalance:function(){
    var url = '/yuanmai_we/user/activityrecharge/list';
    app.loadDataFromServer(url,this.loadBalanceCallBack,{},'get',true);
  },
  loadBalanceCallBack:function(res){
    console.log(res);
    for(var i=0;i<res.length;i++){
      res[i].recharge = parseInt(res[i].recharge).toString();
    }
    this.setData({
      sum: res[0].recharge,
      sumlist: res
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  nameInput:function(e){
    this.setData({
      username: e.detail.value
    });
  },
  phoneInput:function(e){
    this.setData({
      phone: e.detail.value
    });
  },
  codeInput:function(e){
    this.setData({
      msgCode: e.detail.value
    });
  },
  radioChange: function (e) {
    console.log(e.detail.value);
    var sexval = e.detail.value == '女' ? '1':'0';
    this.setData({
      sexval: sexval
    });
  },
  bindDateChange: function (e) {
    var dateval = e.detail.value;
    var vals = dateval.split('-');
    var birth = this.data.birth;
    birth.year = vals[0];
    birth.month = vals[1];
    birth.day = vals[2];
    this.setData({
      birthdaystr: dateval,
      birth: birth
    });
  },
  setIsDefault: function () {
    var isAgree = this.data.isAgree;
    if (isAgree == '1') {
      isAgree = '0';
    }
    else {
      isAgree = '1';
    }
    this.setData({ isAgree: isAgree });
  },
  setIsDefault2:function(){
    var isAgree2 = this.data.isAgree2;
    if (isAgree2 == '1') {
      isAgree2 = '0';
    }
    else {
      isAgree2 = '1';
    }
    this.setData({ isAgree2: isAgree2 });
  },
  changeRechageType:function(e){
    var rctype = e.currentTarget.id;
    if(rctype == this.data.rctype){
      return;
    }
    this.setData({
      rctype: rctype
    });
  },
  changeSum:function(e){
    var sum = e.currentTarget.id;
    if(sum == this.data.sum){
      return;
    }
    this.setData({
      sum: sum
    });
  },
  changeEyeOpen:function(){
    var isPassword = this.data.isPassword;
    if (isPassword == true) {
      isPassword = false;
    }
    else {
      isPassword = true;
    }
    this.setData({ isPassword: isPassword });
  },
  scanCard:function(){
    wx.scanCode({
      success:function(res){
        console.log(res);
      }
    });
  },
  backToOnlineRecharge:function(){
    this.setData({
      rctype: '1'
    });
  },
  checkMoneyDetail:function(){
    wx.redirectTo({
      url: './moneydetail/moneydetail',
    });
  },
  setMoneyPwd:function(){
    wx.redirectTo({
      url: './password/password?target=set',
    });
  },
  checkRule:function(){
    this.setData({tipshow:true});
  },
  hideTipContent:function(){
    this.setData({tipshow:false});
  },
  submitInfo: function () {
    if (this.data.isAgree != '1'){
      wx.showToast({
        title: '请同意相关协议',
        icon: 'none'
      });
      return;
    }
    if (this.data.username == '' || this.data.phone == '' || this.data.msgCode == '') {
      wx.showToast({
        title: '信息不完整',
        icon: 'none'
      });
      return;
    }
    if (!utils.isPhoneAvailable(this.data.phone)) {
      wx.showToast({
        title: '手机号码格式不正确',
        icon: 'none'
      });
      return;
    }
    var url = '/yuanmai_we/usercenter/user/registerForVip';
    var params = {
      __zaofans: true,
      USERNAME: this.data.username,
      USERSEX: this.data.sexval,
      MOBILE: this.data.phone,
      USERBIRTHDAY: this.data.birthdaystr,
      CHECKCODE: this.data.msgCode
    }
    app.loadDataFromServer(url, this.submitCallBack, params, 'post', true);
  },
  submitCallBack: function (res) {
    console.log(res);
    if (res.success) {
      wx.showToast({
        title: '保存成功',
        duration: 1000
      });
      app.globalData.personInfo = {
        USERNAME: this.data.username,
        USERSEX: this.data.sexval,
        MOBILE: this.data.phone,
        USERBIRTHDAY: this.data.birthdaystr,
      };
      var that = this;
      var delayid = setTimeout(function () {
        clearTimeout(delayid);
        that.setData({
          isFirst: '0'
        });
      }, 1000);
    }
    else {
      wx.showToast({
        title: res.error,
        icon: 'none'
      });
    }
  },
  msgPhoneInput: function (e) {
    this.setData({
      msgPhone: e.detail.value
    });
  },
  msgCodeInput: function (e) {
    this.setData({
      msgCode: e.detail.value
    });
  },
  getVerifyCode: function (e) {
    if (this.data.phone == '') {
      wx.showToast({
        title: '请输入手机号码',
        icon: 'none'
      });
      return;
    }
    if (!utils.isPhoneAvailable(this.data.phone)) {
      wx.showToast({
        title: '手机号码格式不正确',
        icon: 'none'
      });
      return;
    }
    var url = '/yuanmai_we/activity/sms/sendCheckCode';
    var property = {
      "MOBILE": this.data.phone,
      "ACTION": "updateMobile"
    };
    var params = {
      datas: JSON.stringify(property),
      __zaofans: true
    }
    app.loadDataFromServer(url, this.sendMsgActionCallBack, params, 'post', true);
  },
  sendMsgActionCallBack: function (res) {
    console.log(res);
    if (res.success) {
      wx.showToast({
        title: '发送成功',
      });
    }
    else {
      wx.showToast({
        title: res.errMsg,
        icon: 'none'
      });
    }
  },
  scanGift:function(){
    console.log('gift');
  },
  //---------------------充值-----------------------
  rechargeAction:function(){
    wx.showLoading({
      title: '',
    });
    var url = '/weappmall/user/order/create';
    var trade_no = "CZ" + UUID.uuid(30);
    var bodystr = this.data.sum + '元充值卡';
    var openid = app.globalData.openID;
    var sessionid = app.globalData.sessionID;
    var params = {
      uname: "weappmall ",//固定值
      out_trade_no: trade_no,//CZ+30位随机数
      body: bodystr,//xxx元充值卡 
      spbill_create_ip:"127.0.0.1",
      trade_type:"JSAPI",
      openId: openid,
      attach: sessionid,
      total_fee: this.data.sum
    };
    app.loadDataFromServer(url, this.rechargeCallBack,params,'post')
  },
  rechargeCallBack:function(res){
    console.log(res);
    if(res.code == '0000'){
      var jsapi = res.data;
      var packagestr = "prepay_id=" + jsapi.prepay_id;
      wx.requestPayment({
        'appId': 'wx93176ec2a9cee7e1',
        'timeStamp': jsapi.timeStamp,
        'nonceStr': jsapi.nonceStr,
        'package': packagestr,
        'signType': 'MD5',
        'paySign': jsapi.paySign,
        'success': function (res) {
          wx.hideLoading();
          wx.showToast({
            title: '支付成功',
            duration: 1000
          });
          var delayid = setTimeout(function () {
            clearTimeout(delayid);
            wx.redirectTo({
              url: './moneydetail/moneydetail',
            });
          }, 1000);
        },
        'fail': function (res) {
          wx.hideLoading();
        }
      });
    }
    else{
      wx.hideLoading();
    }
  }
})